//
// winter - Direct2D GUI framework.
// Copyright (C) 2009 Aleksandar Dezelin 
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef SINGLETON_HOST_H
#define SINGLETON_HOST_H

#pragma once
#include "noncopyable.h"
#include <memory>
#include <stdlib.h>
#include <Windows.h>

namespace winter {
namespace platform {

/// <summary>
///     Implements singleton using one-init Windows API.
/// </summmary>
template<class T>
class singleton_host : public services::noncopyable {
public:

  /// <summary>
  ///     Returns and initializes the singleton instance on first call.
  /// </summary>
  /// <returns>
  ///     The singleton instance.
  /// </returns>
  static T* instance() {
    void* context;
    if(::InitOnceExecuteOnce(&_once, create_instance, NULL, &context))
      return static_cast<T*>(context);
    else
      return 0;
  }

  /// <summary>
  ///     Destroys the singleton instance.
  ///     NOTE: not thread safe.
  /// </summary>
  static void destroy() {
    // Convert stored pointer to instance pointer
    T* p = reinterpret_cast<T*>((reinterpret_cast<INT_PTR>(_once.Ptr) >> 
      RTL_RUN_ONCE_CTX_RESERVED_BITS) << RTL_RUN_ONCE_CTX_RESERVED_BITS);
    delete p;
    // Reset one-time initialization structure. 
    ::InitOnceInitialize(&_once);
  }

private:
  explicit singleton_host();
  ~singleton_host();

  static BOOL CALLBACK create_instance(PINIT_ONCE InitOnce, 
    PVOID Parameter, PVOID *lpContext) {
    try {
      std::auto_ptr<T> p(new T());
      schedule_for_destruction(destroy);
      *lpContext = p.release();
    } catch(...) {
      return FALSE;
    }

    return TRUE;

    UNREFERENCED_PARAMETER(InitOnce);
    UNREFERENCED_PARAMETER(Parameter);
  }

  static void schedule_for_destruction(void (*destroy_fun)()) {
    std::atexit(destroy_fun);
  }

  static INIT_ONCE _once;
};

template<class T>
INIT_ONCE singleton_host<T>::_once = INIT_ONCE_STATIC_INIT;

}
}

#endif // SINGLETON_HOST_H
